<?php
class MY_Parser extends CI_Parser {

    const LANG_REPLACE_REGEXP     = '!\{_\s*(?<key>[^\}]+)\}!';
    const INCLUDE_REPLACE_REGEXP  = '!\{_include\s*(?<key>[^\}]+)\}!';
    const WIDGET_REPLACE_REGEXP   = '!\{_widget\s*(?<key>[^\}]+)\}!';
    static $CI = null;
    private $_data = "";


    public function parse($template, $data='', $piece=FALSE) {
        $this->CI = get_instance();
        $themeName = $this->CI->config->item('theme_name');
        $this->_data = $data;
        //prepare data
        $data['imagepath']  = base_url("/themes/".$themeName."/images");
        $data['stylepath']  = base_url("/themes/".$themeName."/style");
        $data['jspath']     = base_url("/themes/".$themeName."/js");
        $data['themepath']  = base_url("/themes/".$themeName);


        $data['maincontent'] = $this->CI->load->view("themes/".$themeName."/".$template, $data, TRUE);
        if(!$piece){
          $template = $this->CI->load->view("themes/".$themeName."/master.php", $data, TRUE);
        }else{
          $template = $data['maincontent'];
        }

        $template = $this->replace_include_keys($template);
        $template = $this->replace_widget_keys($template);
        $template = $this->replace_lang_keys($template);
        if(count(PageUtil::getVar("title"))>0){
          preg_match("#\<title\>(.*)\<\/title\>#i",$template,$matches);
          if(!empty($matches[1])){
            $originalTitle = $matches[1];
            $newTitle = $originalTitle." -";
          }else{
            $originalTitle = "";
            $newTitle = "";
          }
          foreach(PageUtil::getVar("title") AS $title){
            $newTitle .= " ".$title;
          }
          if(empty($originalTitle)){
            $template = str_replace("<title>".$originalTitle."</title>","<title>".trim($newTitle)."</title>",$template);
          }else{
            $template = str_replace($originalTitle,$newTitle,$template);
          }
        }

        if(count(PageUtil::getVar("keywords"))>0){
          preg_match("#\<meta name=\"keywords\" content=\"(.*)\" \/\>#i",$template,$matches);
          if(!empty($matches[1])){
            $originalKeywords = $matches[1];
          }else{
            $originalKeywords = "";
          }
          
          $newKeywords = PageUtil::getVar("keywords");
          if(!empty($originalKeywords)){
            $newKeywords[] = $originalKeywords;
          }
          $newKeywords = implode(", ", $newKeywords);
          if(empty($originalKeywords)){
            $template = str_replace("name=\"keywords\" content=\"".$originalKeywords."\"","name=\"keywords\" content=\"".trim($newKeywords)."\"",$template);
          }else{
            $template = str_replace($originalKeywords,$newKeywords,$template);
          }
          
        }
        unset($matches);
        if(count(PageUtil::getVar("description"))>0){
          preg_match("#\<meta name=\"description\" content=\"(.*)\" \/\>#i",$template,$matches);
          if(!empty($matches[1])){
            $originalDescriptions = $matches[1];
          }else{
            $originalDescriptions = "";
          }
          $newDescriptions = $originalDescriptions;
          foreach(PageUtil::getVar("description") AS $description){
            $newDescriptions .= " ".$description;
          }
          if(empty($originalDescriptions)){
            $template = str_replace("name=\"description\" content=\"".$originalDescriptions."\"","name=\"description\" content=\"".trim($newDescriptions)."\"",$template);
          }else{
            $template = str_replace($originalDescriptions,$newDescriptions,$template);
          }
        }
        unset($matches);
        if(count(PageUtil::getVar("stylesheet"))>0||count(PageUtil::getVar("javascript"))>0){
          $newHead = "";
          if(count(PageUtil::getVar("stylesheet"))>0){
            foreach(PageUtil::getVar("stylesheet") AS $stylesheet){
              $newHead .= "\n".$stylesheet;
            }
          }
          if(count(PageUtil::getVar("javascript"))>0){
            foreach(PageUtil::getVar("javascript") AS $javascript){
              $newHead .= "\n".$javascript;
            }
          }
          $template = str_replace("</head>",$newHead."\n</head>",$template);
        }

        if(count(PageUtil::getVar("javascript_body")) > 0){
          $bodyScript = "";
          foreach(PageUtil::getVar("javascript_body") AS $javascript){
              $bodyScript .= "\n".$javascript;
          }
          $template = str_replace("</body>",$bodyScript."\n</body>",$template);
        }

        return $this->_parse($template, $data);
    }

    protected function replace_lang_keys($template) {
        return preg_replace_callback(self::LANG_REPLACE_REGEXP, array($this, 'replace_lang_key'), $template);
    }

    protected function replace_include_keys($template) {
        return preg_replace_callback(self::INCLUDE_REPLACE_REGEXP, array($this, 'replace_include_key'), $template);
    }

    protected function replace_widget_keys($template) {
        return preg_replace_callback(self::WIDGET_REPLACE_REGEXP, array($this, 'replace_widget_key'), $template);
    }

    protected function replace_lang_key($key) {
        return $this->CI->lang->line($key[1]);
    }

    protected function replace_include_key($key) {
      $themeName = $this->CI->config->item('theme_name');
      $template = $this->CI->load->view("themes/".$themeName."/_Includes/".$key["1"].".php", $this->_data, TRUE);
      $template = $this->replace_lang_keys($template);

      return  $this->_parse($template,  $this->_data);
    }

    protected function replace_widget_key($key) {
      if(file_exists(APPPATH."widgets/".strtolower($key["1"])."_widget.php")){
        require_once(APPPATH."widgets/".strtolower($key["1"])."_widget.php");

        $class = strtolower($key["1"])."_widget";
        $WIDGET = new $class;

        return  $WIDGET->run();
      }else{
        return;
      }
    }

    function _parse($template, $data)
    {
    	if ($template == '')
    	{
    		return FALSE;
    	}

      if($data != "")
    	foreach ($data as $key => $val)
    	{
    		if (is_array($val))
    		{
    			$template = $this->_parse_pair($key, $val, $template);
    		}
    		else
    		{
    			$template = $this->_parse_single($key, (string)$val, $template);
    		}
    	}

    	return $template;
    }
}
?>